﻿/*
* Copyright 2009-2010 AKABANA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
using System;
using System.IO;
using System.Text;
using Akabana.Amf.Serializer;

namespace Akabana.Amf.IO
{
    public class AmfWriter : BinaryWriter
    {
        private IAmfSerializer _amfSerializer;

        public IAmfSerializer amfSerializer
        {
            get { return _amfSerializer; }
            set { _amfSerializer = value; }
        }

        public ushort version { get; set; }

        public AmfWriter(Stream output, ushort version)
            : base(output, Encoding.UTF8)
        {
            this.version = version;
            _amfSerializer = AmfSerializerFactory.CreateSerializer(version, this);
        }

        public void WriteByte(uint value)
        {
            Write((byte)value);
        }

        public void WriteByte(int value)
        {
            Write((byte)value);
        }

        public void WriteByte(byte value)
        {
            Write(value);
        }

        public void WriteU16(ushort value)
        {
            Write((byte)((value >> 8) & 0xFF));
            Write((byte)(value & 0xFF));
        }

        public void WriteS16(short value)
        {
            Write((byte)((value >> 8) & 0xFF));
            Write((byte)(value & 0xFF));
        }

        public void WriteU32(uint value)
        {
            Write((byte)((value >> 24) & 0xFF));
            Write((byte)((value >> 16) & 0xFF));
            Write((byte)((value >> 8) & 0xFF));
            Write((byte)(value & 0xFF));
        }

        public void WriteUtfString(string value)
        {
            var bytes = Encoding.UTF8.GetBytes(value);

            WriteU16((ushort)bytes.Length);
            Write(bytes);
        }

        public void WriteNumber(double value)
        {
            var byteArray = BitConverter.GetBytes(value);
            Write(byteArray[7]);
            Write(byteArray[6]);
            Write(byteArray[5]);
            Write(byteArray[4]);
            Write(byteArray[3]);
            Write(byteArray[2]);
            Write(byteArray[1]);
            Write(byteArray[0]);
        }

        public void WriteObject(object value)
        {
            _amfSerializer.Serialize(value);
        }
    }
}
